/*
 * Materiale didattico per corso sulle Applicazioni Internet 
 * 
 * Copyright (c) 2005-2008 Link.it srl (http://link.it). All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * @author Lorenzo Nardi (nardi80@gmail.com)
 */


package isi.http;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;



public class ClientHTTP {

	
    public final static void main(String[] args) throws Exception {
    	
    	String queryString = "http://localhost:8081/shop/acquisti";
    	
    	HttpClient httpclient = new DefaultHttpClient();
    	 
		// Prepariamo la richiesta
		HttpPost httppost = new HttpPost(queryString); 
		
		//Costruisco il DOM dell'ordine
		Document ordine = getOrdine();
		
		//Converto il DOM in stringa
		String ordineXML = toString(ordine);
		StringEntity content = new StringEntity(ordineXML);
		content.setContentType("text/xml");
		
		httppost.setEntity(content);
		
		
		for(int buys = 0; buys<5; buys++){
	    	// Eseguiamo la richiesta e prendiamo la risposta
	    	HttpResponse response = httpclient.execute(httppost);
	    	 
	    	// Stampiamo Status Line e Headers
	    	System.out.println("============= Response ===============");
	    	System.out.println(response.getStatusLine());
			// Stampiamo il contenuto della risposta
			HttpEntity entity = response.getEntity();
				 
			if (entity != null) {
				InputStream instream = entity.getContent();
				try {
					String s = null;
					BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
	
					while((s = reader.readLine()) != null) System.out.println(s);
					
				} catch (Exception e) {
					httppost.abort();
					throw e;
				} finally {
					instream.close();
				}
			}
		}
    }
    
    private static Document getOrdine(){
        try{
            //Crea un istanza di DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //Ottieni il DocumentBuilder
            DocumentBuilder parser = factory.newDocumentBuilder();
            //Crea un DOM Document vuoto
            Document doc = parser.newDocument();
            // Creo l'elemento ordine con l'attributo corriere e lo appendo al documento
            Element ordine = doc.createElementNS("http://www.shop.com/ns", "ns:ordine");
            //ordine.setAttribute("corriere", "DHL");
            doc.appendChild(ordine);
            
            //Creo l'elemento articolo e lo aggiungo all'ordine
            Element articolo = doc.createElement("ns:articolo");
            Element nome = doc.createElement("ns:nome");
            Element quantita = doc.createElement("ns:quantita");
            nome.appendChild(doc.createTextNode("SONYPS3"));
            quantita.appendChild(doc.createTextNode("3"));
            articolo.appendChild(nome);
            articolo.appendChild(quantita);
            
            ordine.appendChild(articolo);
            
            return doc;
            
        }
        catch(Exception e){
              System.out.println(e.getMessage());
        }
        return null;
    }
    
    private static String toString(Document doc){
    	try{
	    	DOMSource domSource = new DOMSource(doc);
	        StringWriter writer = new StringWriter();
	        StreamResult result = new StreamResult(writer);
	        TransformerFactory tf = TransformerFactory.newInstance();
	        Transformer transformer = tf.newTransformer();
	        transformer.transform(domSource, result);
	        return writer.toString();
    	}
    	catch(TransformerConfigurationException e){
    		e.printStackTrace();
    	}
    	catch(TransformerException e){
    		e.printStackTrace();
    	}
    	return "";
    }
}

